#include <Arduino.h>
#include <WiFi.h>

const char *ssid = "IOTNET";
const char *passwd = "12345678";
//const char *host = "10.175.5.243";
//const char *host = "192.168.137.1";
const char *host = "60.205.234.19";
const uint16_t channelBindPort = 8848;

#define SERIAL_BUFFER_SIZE 30000 // 串口缓冲区大小
char serialBuffer[SERIAL_BUFFER_SIZE]; // 串口缓冲区
int serialBufferIndex = 0; // 当前缓冲区索引

char serial2Buffer[100]; // 串口缓冲区
int serial2BufferIndex = 0; // 当前缓冲区索引


uint8_t bind_sn[] = {'O','N'};

const char  *str1="AT\r\n";
const char  *str2="AT+CGMI\r\n";
const char  *str3="AT+CGMR\r\n";
const char  *str4="AT+CPIN?\r\n";
const char  *str5="AT+CSQ\r\n";
const char  *str6="AT+CREG?\r\n";
const char  *str7="AT+CGATT?\r\n";
const char  *str8="AT+SETVOLTE=1\r\n";        
const char  *str9="ATD13221832053;\r\n";
const char  *str10="AT+CLVL=100;\r\n";
const char  *str11="ATA\r\n";
const char  *RING="RING";



 
const int adcPin = 34; // ADC引脚，可以根据需要更改为其他引脚
WiFiClient client; // 声明全局变量
const int buttonPin = 19; // 按键所连接的GPIO引脚
const int buttonPin2 = 15; // 按键2所连接的GPIO引脚
const int buttonPin3 = 35; // 按键3所连接的GPIO引脚


volatile bool buttonPressed = false; // 中断标志，用于指示按键是否被按下
volatile bool buttonPressed2 = false; // 按键2中断标志
volatile bool buttonPressed3 = false; // 按键2中断标志

void IRAM_ATTR buttonISR() {
  buttonPressed = true; // 设置中断标志，表示按键被按下
}
void IRAM_ATTR buttonISR2() {
  buttonPressed2 = true; // 设置按键2中断标志
}
void IRAM_ATTR buttonISR3() {
  buttonPressed3 = true; // 设置按键2中断标志
}



void connectWifi(const char *ssid, const char *passphrase) {
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, passphrase);

    Serial.println("connecting to router... ");
    //等待wifi连接成功
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
    }
    Serial.print("\nWiFi connected, local IP address:");
    Serial.println(WiFi.localIP());
}


void callSerialDataSend() {
    while (Serial2.available()) {
        char c = Serial2.read();
        if (serial2BufferIndex < SERIAL_BUFFER_SIZE - 1) {
            serial2Buffer[serial2BufferIndex++] = c;
        }
        if (c == '\n') {
            serial2Buffer[serial2BufferIndex] = '\0'; // 添加结束符
    
             if((strncasecmp(RING,serial2Buffer,4)==0))
              {
               Serial.println(serial2Buffer);
               Serial2.write(str11);
              }
            // 清空缓冲区
            serial2BufferIndex = 0;
        }
    }
}

void SerialDataSend() {
    while (Serial1.available()) {
        char c = Serial1.read();
        if (serialBufferIndex < SERIAL_BUFFER_SIZE - 1) {
            serialBuffer[serialBufferIndex++] = c;
        }
        if (c == '\n') {
            serialBuffer[serialBufferIndex] = '\0'; // 添加结束符
            serialBuffer[serialBufferIndex+1] = '\n'; // 添加结束符
            
            Serial.println(serialBuffer);
            // 发送数据到 TCP 服务器
            WiFiClient client;
            if (client.connect(host, channelBindPort)) {
              
                // 发送数据
                client.write(serialBuffer, serialBufferIndex+1);
                Serial.println("Data sent to server");
            } else {
                Serial.println("Failed to connect to server");
            }
            // 清空缓冲区
            serialBufferIndex = 0;
        }
    }
}



void setup() {
    //pinMode(2,  OUTPUT); // 开启引脚输出模式
    pinMode(12, OUTPUT); // 开启引脚输出模式
    pinMode(18,INPUT_PULLUP); // 开启引脚输ru模式
    pinMode(21, OUTPUT); // 开启引脚输出模式
    analogReadResolution(12); // 设置 ADC 分辨率为 12 位
    Serial.begin(115200); // 初始化默认的串口 UART0
    Serial2.begin(115200); // 初始化 UART1
    Serial1.begin(115200, SERIAL_8N1, 4, 32); // 初始化UART1，波特率115200，数据位8，无校验位，1个停止位，引脚映射到GPIO 4（RX）和GPIO 32（TX）
          
    pinMode(buttonPin, INPUT_PULLUP); // 将按键引脚设置为输入模式，并启用上拉电阻
    pinMode(buttonPin2, INPUT_PULLUP); // 将按键引脚设置为输入模式，并启用上拉电阻
    attachInterrupt(digitalPinToInterrupt(buttonPin), buttonISR, FALLING); // 将中断函数与按键引脚的下降沿触发关联
    attachInterrupt(digitalPinToInterrupt(buttonPin2), buttonISR2, FALLING); // 将按键2中断函数与引脚的下降沿触发关联
    attachInterrupt(digitalPinToInterrupt(buttonPin3), buttonISR2, FALLING); // 将按键2中断函数与引脚的下降沿触发关联

    connectWifi(ssid, passwd);

    Serial2.write(str1);
    Serial2.write(str2);
    Serial2.write(str3);
    Serial2.write(str4);
    Serial2.write(str5);
    Serial2.write(str6);
    Serial2.write(str7);
    Serial2.write(str8);
    Serial2.write(str9);
   
    Serial2.write(str10);
   
    while (!client.connect(host, channelBindPort)) {
    Serial.println("Connection to server failed, retrying...");
    delay(1000);
    }
    Serial.println("Connected to server");
  
   if (Serial2.available()) {
        char receivedChar = Serial2.read();
        Serial.write(receivedChar);
    }

}

void loop() {
    

   if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false; // 重置中断标志
    Serial2.write(str9);
    
  // 在这里添加你想要执行的按键被按下时的代码
  }
    SerialDataSend();
    callSerialDataSend();
  if (buttonPressed2) {
    
    digitalWrite(12, HIGH);
    delay(1000);
    digitalWrite(12, LOW);
    delay(500);
    digitalWrite(12, HIGH);
    delay(1000);
    digitalWrite(12, LOW);
    delay(500);
    digitalWrite(12, HIGH);
    delay(1000);
    digitalWrite(12, LOW);
    delay(1000);
    buttonPressed2 = false;
  }


  digitalWrite(12, LOW);

  if(digitalRead(18)==HIGH)
{
  digitalWrite(12, HIGH);
}
digitalWrite(12, LOW);



 if(digitalRead(18)==HIGH)
{
  digitalWrite(12, HIGH);
    //  digitalWrite(12, LOW);
    
}
digitalWrite(18, HIGH);

   
  


  int adcValue = analogRead(adcPin); // 读取 ADC 值

  float voltage = adcValue * (3.3 / 4095); // 将 ADC 值转换为电压值，假设 Vref = 3.3V
 // Serial.print("ADC Value: ");
  //Serial.print(adcValue);
 // Serial.print(", Voltage: ");
 // Serial.print(voltage);
 // Serial.println("V");
  if(voltage<0.8)
  {
  digitalWrite(21,LOW);
  //Serial.println("21, LOW");
  }
  if(voltage>1)
  {
  // Serial.println("21, HIGH");
   digitalWrite(21, HIGH);
  }
  
}
